package com.ossjk.oa.system.service.impl;

import com.ossjk.core.util.CommonUtil;
import com.ossjk.oa.system.entity.Department;
import com.ossjk.oa.system.mapper.DepartmentMapper;
import com.ossjk.oa.system.service.IDepartmentService;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author chair
 * @since 2019-01-30
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

	@Override
	public Department selectByEid(String eid) {
		// TODO Auto-generated method stub
		return this.baseMapper.selectByEid(eid);
	}

	@Override
	public List<Department> selectSubByPid(String pid) {
		List<Department> departments = this.selectList(Condition.create().orderBy("level").orderBy("sort"));
		return filterSub(pid, departments);
	}

	@Override
	public List<String> selectSubIdByPid(String pid) {
		List<Department> departments = this.selectList(Condition.create().orderBy("level").orderBy("sort"));
		return filterSubId(pid, departments);
	}

	/**
	 * 过滤子集
	 * 
	 * @param id
	 * @param list
	 * @param list2
	 */
	private List<Department> filterSub(String pid, List<Department> departments) {
		List<Department> subs = null;
		if (!CommonUtil.isBlank(departments)) {
			for (Department department : departments) {
				if (pid.equals(department.getPid())) {
					if (CommonUtil.isBlank(subs)) {
						subs = new ArrayList<Department>();
					}
					subs.add(department);
					List<Department> list = filterSub(department.getId(), departments);
					if (!CommonUtil.isBlank(list)) {
						subs.addAll(list);
					}
				}
			}

		}
		return subs;

	}

	/**
	 * 过滤子集id
	 * 
	 * @param id
	 * @param list
	 * @param list2
	 */
	private List<String> filterSubId(String pid, List<Department> departments) {
		List<String> subs = null;
		if (!CommonUtil.isBlank(departments)) {
			for (Department department : departments) {
				if (CommonUtil.isBlank(subs)) {
					subs = new ArrayList<String>();
				}
				if (pid.equals(department.getPid())) {
					subs.add(department.getId());
					List<String> list = filterSubId(department.getId(), departments);
					if (!CommonUtil.isBlank(list)) {
						subs.addAll(list);
					}
				}
			}
		}
		return subs;

	}

	@Override
	public List<Map<String, String>> selectVo() {
		// TODO Auto-generated method stub
		return this.baseMapper.selectVo();
	}
}
